<template>
  <div
    class="new-group"
    v-loading="saveloading.status"
    :element-loading-text="saveloading.txt"
  >
    <nav-header>
      <template slot="menuBefore">
        <li>
          <router-link to="/teaching/group/circle-group" tag="a"
            >圈组列表</router-link
          >
        </li>
        <li class="gap">&gt;</li>
      </template>
      <li>新建圈组</li>
    </nav-header>

    <div class="publishFrom">
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="封面图片" prop="imageUrl2">
          <uploader-dom
            :options="uploadOptions"
            :picture="ruleForm.picture"
            @imgListen="getImg"
          ></uploader-dom>
        </el-form-item>
        <el-form-item label="圈组名称" prop="name">
          <el-input
            v-model.trim="ruleForm.name"
            placeholder="20个字符内"
          ></el-input>
        </el-form-item>
        <template v-if="!this.$store.state.platformInformation">
          <ul>
            <li class="publishFrom_seleck">
              <el-form-item label="学段" prop="study_section_id">
                <el-select
                  v-model="ruleForm.study_section_id"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in orgLevel2"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="年级" prop="grade_id">
                <el-select
                  v-model="ruleForm.grade_id"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in orgLevel3"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </li>
            <li class="publishFrom_seleck">
              <el-form-item label="科目" prop="subject_id">
                <el-select
                  v-model="ruleForm.subject_id"
                  filterable
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in orgSubject"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </li>
          </ul>
        </template>
        <!-- 单级版 -->
        <template v-if="!this.$store.state.checkLevel">
          <el-form-item label="邀请成员" prop="teacher_id">
            <el-tag
              :key="tag"
              v-for="tag in dynamicTags"
              closable
              :disable-transitions="false"
              @close="deleteTag(tag)"
            >
              {{ tag }}
            </el-tag>
            <el-button
              class="button-new-tag"
              size="small"
              @click="getTeacherList(1)"
              >+ 邀请成员</el-button
            >
          </el-form-item>
        </template>

        <!-- 多级版 --------------------------------------->
        <template v-else>
          <el-form-item label="邀请成员" prop="teacher_id">
            <el-button
              class="button-new-tag"
              size="small"
              @click="memeberVisible = true"
              >+ 邀请成员</el-button
            >
            <div
              class="members-checked"
              v-if="checkedData && checkedData.length > 0"
            >
              <p class="title">已邀请成员</p>
              <div class="container">
                <template v-for="item of checkedData">
                  <div
                    class="tree-top-level"
                    :key="item.app_code"
                    v-if="item.children.length > 0"
                  >
                    <div class="row">
                      <label>{{ item.name }}：</label>
                    </div>
                    <el-tag
                      size="small"
                      closable
                      v-for="member in item.children"
                      :key="member.id"
                      @close="cancelCheck(member)"
                    >
                      {{ member.name }}
                    </el-tag>
                  </div>
                </template>
              </div>
            </div>
          </el-form-item>
        </template>

        <el-form-item style="margintop: 40px">
          <el-button @click="resetForm()">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">保存</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 邀请成员 -->
    <el-dialog
      title="邀请成员"
      :visible.sync="selectResourceView"
      width="800px"
      custom-class="alBox"
      :before-close="cancel"
      :close-on-click-modal="false"
    >
      <div
        class="releaseTK"
        v-loading="loading.status"
        :element-loading-text="loading.txt"
      >
        <div class="releaseTK_h clear">
          <div class="resourceType fl">
            <span>学段</span>
            <el-select
              v-model="teacherParam.study_section_id"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in orgLevel2Teacher"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <div class="resourceType fl">
            <span>年级</span>
            <el-select
              v-model="teacherParam.grade_id"
              filterable
              placeholder="请选择"
            >
              <el-option
                v-for="item in orgLevel3Teacher"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </div>
          <!--  -->
          <div class="fr" style="margin-left: 20px">
            <el-button type="primary" @click="getTeacherList(2)"
              >搜索</el-button
            >
            <el-button type="primary" @click="getTeacherList(1)"
              >重置</el-button
            >
          </div>
          <div class="resourceSearch fr">
            <el-input placeholder="教师名" v-model="teacherParam.n_n_e">
              <i
                slot="suffix"
                class="el-input__icon el-icon-search"
                @click="getTeacherList(2)"
              ></i>
            </el-input>
          </div>
        </div>
        <div class="resourceData">
          <template>
            <el-table
              border
              ref="multipleTable"
              :data="TeacherList"
              tooltip-effect="dark"
              :row-key="getRowKeys"
              style="width: 100%"
              @selection-change="tableSelectionChange"
            >
              <el-table-column
                type="selection"
                :reserve-selection="true"
                width="55"
                fixed
              >
              </el-table-column>
              <el-table-column prop="number" label="登录账户" width="">
              </el-table-column>
              <el-table-column prop="name" label="用户名" width="">
              </el-table-column>
              <el-table-column
                prop="sub_name"
                label="科目"
                width=""
                show-overflow-tooltip
              >
              </el-table-column>
              <el-table-column
                prop="org_name"
                label="组织架构"
                width=""
                show-overflow-tooltip
              >
              </el-table-column>
            </el-table>
          </template>

          <div class="pageBox table-pagination" v-show="total_number > 10">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="teacherParam.page"
              :page-sizes="[10, 20, 30, 40, 50, 100]"
              :page-size="teacherParam.size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total_number"
            >
            </el-pagination>
            <div class="pagination-button">
              <el-button
                @click="getTeacherList(1)"
                type="primary"
                icon="el-icon-refresh"
                circle
                title="刷新数据"
                size="mini"
              >
              </el-button>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer releaseTK_btn">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirmTeacher()">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 多级版 邀请成员弹窗 -->
    <el-dialog
      title="选择成员"
      class="multi-dialog"
      :visible.sync="memeberVisible"
      @close="handleClose"
    >
      <orgTree ref="organization"></orgTree>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="cancelAddTeacher">取消</el-button>
        <el-button size="small" type="primary" @click="sureMemeber"
          >确定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import uploaderDom from "@/components/common/uploader-image";
import orgTree from "@/components/common/organization-tree";

export default {
  data() {
    return {
      selMemory: [], // 未保存之前的值
      loading: {
        status: false,
        txt: "获取数据...",
      },
      saveloading: {
        status: false,
        txt: "保存数据...",
      },
      ruleForm: {
        name: "", //视频名称
        study_section_id: "", //学段
        grade_id: "", //年级
        subject_id: "", //科目
        picture: "",
        teacher_id: [],
      },
      rules: {
        name: [
          { required: true, message: "请输入圈组名称", trigger: "blur" },
          {
            min: 3,
            max: 20,
            message: "长度在 3 到 20 个字符",
            trigger: "blur",
          },
        ],
        study_section_id: [
          { required: true, message: "请选择学段", trigger: "change" },
        ],
        grade_id: [
          { required: true, message: "请选择年级", trigger: "change" },
        ],
        subject_id: [
          { required: true, message: "请选择科目", trigger: "change" },
        ],
        teacher_id: [
          { required: true, message: "请选择邀请的老师", trigger: "change" },
        ],
      },
      selectResourceView: false, //选择资源
      multipleSelection: [], //选择试卷--checked
      resourceType3: "", //选择资源-资源类型--val
      resourceSearch2: "",
      currentPage4: 1,
      Study_id: "",
      grade_id: "",
      dynamicTags: [],
      TeacherList: [],
      total_number: 0,
      teacherParam: {
        status: [1],
        role_id: 6,
        study_section_id: null,
        grade_id: null,
        org_id: null,
        n_n_e: "",
        page: 1,
        size: 10,
        data_type: 2,
      },
      orgLevel2Param: {
        //获取学段参数
        level: 2,
        pid: null,
        direction: "balance",
      },
      orgLevel3Param: {
        //获取年级参数
        level: 3,
        pid: null,
        direction: "balance",
      },
      orgLevel2: [],
      orgLevel3: [],
      orgSubject: [],
      subjectParam: {
        //获取科目,版本，参数
        type: 2,
        org_id: null,
        status: 1,
      },
      orgLevel2TeacherParam: {
        //获取学段参数
        level: 2,
        pid: null,
        direction: "balance",
      },
      orgLevel3TeacherParam: {
        //获取年级参数
        level: 3,
        pid: null,
        direction: "balance",
      },
      orgLevel2Teacher: [],
      orgLevel3Teacher: [],

      statusText: {
        success: "上传成功",
        error: "上传出错",
        uploading: "正在上传...",
        paused: "暂停",
        waiting: "等待上传",
      },
      selectFileOrNot: false, //是否选中文件
      uploadOrNot: false, //是否已经上传
      uploadInfo: {
        file_name: "",
        file_path: "",
        file_size: 0,
      },
      attrs: {
        accept: ["image/*"],
      },
      uploadOptions: {
        target: this.BASE_URL + "/api/resource/res_upload",
        testChunks: false,
        headers: { Authorization: `Bearer ` + this.$g.access_token },
      },
      selectFileShow: true, //是否显示选择文件按钮
      uploadRetryTimes: 100, //文件最大重传次数
      previewImgURL: "",
      selected: [],

      // 多级版
      memeberVisible: false,
      checkedData: [],
      checkedIds: "",
    };
  },
  created() {
    this.getOrgLevel2();
    this.getOrgLevel2Teacher();
    this.getOrgLevel3Teacher();
  },
  watch: {
    "ruleForm.study_section_id": {
      handler(newVal, oldVal) {
        this.ruleForm.grade_id = null;
        this.ruleForm.subject_id = null;

        this.orgLevel3Param.pid = newVal;
        this.getOrgLevel3();

        this.subjectParam.org_id = newVal;
        this.getSubject();
      },
    },
    "ruleForm.grade_id": {
      handler(newVal, oldVal) {
        this.ruleForm.subject_id = null;
        this.subjectParam.org_id = newVal;
        this.getSubject();
      },
    },
    "teacherParam.study_section_id": {
      handler(newVal, oldVal) {
        this.teacherParam.grade_id = null;

        this.orgLevel2TeacherParam.pid = newVal;
        if (newVal !== null) {
          this.teacherParam.org_id = newVal;
        }

        this.getOrgLevel3Teacher();
        this.getTeacherList();
      },
    },
    "teacherParam.grade_id": {
      handler(newVal, oldVal) {
        if (newVal !== null) {
          this.teacherParam.org_id = newVal;
        } else {
          this.teacherParam.org_id = this.teacherParam.study_section_id;
        }
        this.getTeacherList();
      },
    },
  },
  methods: {
    /**
     * 取消邀请老师操作
     */
    cancel() {
      this.selectResourceView = false;
      this.selected = this.selMemory;
    },
    saveGroup() {
      let multiParams
      if(this.$store.state.checkLevel) {
          multiParams = {
            picture: this.ruleForm.picture,
            name: this.ruleForm.name,
            study_section_id: this.ruleForm.study_section_id,
            grade_id: this.ruleForm.grade_id,
            subject_id: this.ruleForm.subject_id,
            join_user: this.$refs.organization.checkedIds,
            create_id: this.$store.getters.userInfo.id,
            status: 1,
          };
      }
      let apiUrl = this.$store.state.checkLevel ? "api/group/group_list" : "api/group/manage_group";
      let params = this.$store.state.checkLevel ? multiParams : this.ruleForm;
      let success = (data) => {
        this.saveloading.status = false;
        this.$message.success(data.msg);
        //2后跳回首页
        setTimeout(() => {
          this.$router.push("/teaching/group/circle-group");
        }, 1000);
      };
      let fail = (data) => {
        this.saveloading.status = false;
        this.$message.error(data.msg);
      };
      this.$ajax.post(apiUrl, params, {
        func: { success: success, fail: fail },
      });
    },
    /**
     * row里面有id作为唯一标识
     */
    getRowKeys(row) {
      return row.id;
    },
    /**
     * 选择邀请的老师
     */
    confirmTeacher() {
      if (this.selected.length === 0) {
        this.$message.warning("请选择邀请的老师");
        return false;
      }

      this.ruleForm.teacher_id = [];
      this.dynamicTags = [];
      this.selMemory = this.selected;

      for (let i = 0; i < this.selected.length; i++) {
        let _id = this.selected[i].id;
        let _name = this.selected[i].name;

        if (this.ruleForm.teacher_id.indexOf(_id) === -1) {
          this.ruleForm.teacher_id.push(_id);
          this.dynamicTags.push(_name);
        }
      }

      this.selectResourceView = false;
    },
    /**
     * 获取邀请成员列表
     * @param {Number} key 标识--1:重置变量
     */
    getTeacherList(key) {
      this.selectResourceView = true;
      this.loading.status = true;

      if (key === 1) {
        this.teacherParam = {
          status: [1],
          role_id: 6,
          study_section_id: null,
          grade_id: null,
          org_id: null,
          n_n_e: "",
          page: 1,
          size: 10,
          data_type: 2,
        };
      } else if (key === 2) {
        this.teacherParam.page = 1;
      }

      let success = (res) => {
        this.loading.status = false;
        this.TeacherList = res.data.data;
        this.total_number = res.data.data_sum;

        let _this = this;
        let _temp = deep_clone(this.selected);

        this.$nextTick(() => {
          // 不可以使用 clearSelection，否则翻页后，选中的数据会被清空
          for (let i = 0; i < _this.TeacherList.length; i++) {
            _this.$refs.multipleTable.toggleRowSelection(
              _this.TeacherList[i],
              false
            );
          }

          for (let i = 0; i < _this.TeacherList.length; i++) {
            for (let j = 0; j < _temp.length; j++) {
              if (_temp[j].id == _this.TeacherList[i].id) {
                _this.$refs.multipleTable.toggleRowSelection(
                  _this.TeacherList[i],
                  true
                );
              }
            }
          }

          this.selected = _temp; // 重新赋值，否则删除数据后还是会按上次保存的数据
          // console.log(this.selected)
        });
      };
      let fail = (res) => {
        this.loading.status = false;
        this.$message.error(res.msg);
      };

      this.$ajax.get("api/user/user", {
        params: this.teacherParam,
        func: { success: success },
      });
    },
    //获取学段
    getOrgLevel2() {
      let success = (data) => {
        this.orgLevel2 = data.data;
      };
      if(this.$store.state.checkLevel){
          this.orgLevel2Param.app_code = sessionStorage.getItem('CheckSchoolAppCode')
          this.$ajax.get('api/network/get_platform_org',{params: this.orgLevel2Param,func:{success:success}})
      }else{
          this.$ajax.get('api/org/org',{params: this.orgLevel2Param,func:{success:success}})
      }
    },
    //获取年级
    getOrgLevel3() {
      let success = (data) => {
        this.orgLevel3 = data.data;
      };
      this.$ajax.get("api/org/org", {
        params: this.orgLevel3Param,
        func: { success: success },
      });
    },
    //获取科目
    getSubject() {
      let success = (data) => {
        this.orgSubject = data.data;
      };
      this.$ajax.get("api/cate/subject", {
        params: this.subjectParam,
        func: { success: success },
      });
    },
    //获取学段
    getOrgLevel2Teacher() {
      let success = (data) => {
        this.orgLevel2Teacher = data.data;
        this.orgLevel2Teacher.unshift({ id: null, name: "全部学段" });
      };
      this.$ajax.get("api/org/org", {
        params: this.orgLevel2TeacherParam,
        func: { success: success },
      });
    },
    //获取年级
    getOrgLevel3Teacher() {
      let success = (data) => {
        this.orgLevel3Teacher = data.data;
        this.orgLevel3Teacher.unshift({ id: null, name: "全部年级" });
      };
      this.$ajax.get("api/org/org", {
        params: this.orgLevel3TeacherParam,
        func: { success: success },
      });
    },
    /**
     * 删除邀请成员
     * @param {String} tag 成员名字
     */
    deleteTag(tag) {
      let deleteInx = this.dynamicTags.indexOf(tag);

      if (deleteInx === -1) return false;

      this.dynamicTags.splice(deleteInx, 1);
      this.ruleForm.teacher_id.splice(deleteInx, 1);

      let inx = -1;
      let len = this.selected.length;
      for (let i = 0; i < len; i++) {
        if (this.selected[i].name === tag) {
          inx = i;
          break;
        }
      }
      this.selected.splice(inx, 1);
    },
    //表单验证
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.saveGroup();
        } else {
          return false;
        }
      });
    },
    resetForm() {
      this.$router.go(-1);
    },
    //选中
    tableSelectionChange(val) {
      console.log(val, 1234567)
      this.selected = val;
    },
    handleSizeChange(val) {
      this.teacherParam.page = 1;
      this.teacherParam.size = val;
      this.getTeacherList();
    },
    handleCurrentChange(val) {
      this.teacherParam.page = val;
      this.getTeacherList();
    },
    /**
     * 监听子组件
     */
    getImg(mess) {
      this.ruleForm.picture = mess.file_path;
    },
    // 多级
    sureMemeber() {
      this.memeberVisible = false;
      this.checkedData = this.$refs.organization.checkedData;
      this.checkedIds = this.$refs.organization.checkedIds;
      this.ruleForm.teacher_id = this.checkedIds.split(",").map(Number);
      console.log(this.ruleForm.teacher_id);
    },

    cancelCheck(item) {
      console.log(item.id);

      // 删除已选中的成员id字符串集合中对应的id值：
      let idArr = this.checkedIds.split(",").map(Number);
      idArr = idArr.filter((id) => id != item.id);
      this.checkedIds = idArr.join(",");

      // el-tree 通过key设置 选中状态
      // this.setChecked(idArr);
      this.$refs.organization.setChecked(idArr);
      // 删除已选中对应数据：
      let length = this.checkedData.length;
      for (let i = 0; i < length; i++) {
        const temp = this.checkedData[i].children;
        for (let j = 0; j < temp.length; j++) {
          if (temp[j].id === item.id) {
            temp.splice(j, 1);
          }
        }
      }
      this.$refs.organization.checkedData = this.checkedData;
      this.ruleForm.teacher_id = idArr;
      console.log(idArr);
    },
    cancelAddTeacher() {
      this.memeberVisible = false;
      // console.log(this.$refs.organization._data)
      this.$refs.organization._data.filterText = "";
    },
    handleClose() {
      this.$refs.organization._data.filterText = "";
    },
  },
  components: {
    uploaderDom,
    orgTree,
  },
};
</script>

<style lang="scss">
.new-group {
  .el-form {
    margin-top: 30px;
    max-width: 800px;
  }
  .el-tag {
    border-radius: 0;
    border: 0;
    margin-right: 10px;
  }
  .groupBtn {
    margin-top: 80px;
    padding-left: 80px;
    text-align: left;
  }
}

.publishFrom_ {
  width: 240px;
  height: 135px;
  border: 1px solid #ddd;
  position: relative;
  .avatar-uploader {
    height: 100%;
  }
  .el-upload--text {
    width: 100%;
    height: 100%;
  }
}

.publishFrom_b {
  text-align: center;
  width: 100%;
  > i {
    margin: 20px 0;
  }
  > p {
    font-size: 12px;
    color: #666;
    line-height: 19px;
  }
}

.publishFrom_seleck {
  text-align: center;
  text-align-last: justify;
  > .el-form-item {
    text-align: left;
    text-align-last: initial;
    display: inline-block;
    vertical-align: top;
  }
}

.resourceType {
  > span {
    display: inline-block;
    vertical-align: middle;
    line-height: 32px;
    margin-right: 15px;
  }
  .el-select {
    width: 120px;
  }
  &:nth-of-type(2) {
    margin-left: 15px;
  }
}

.releaseTK_h {
  margin-bottom: 30px;
}

.pageBox {
  margin-bottom: 30px;
  .el-pagination {
    text-align: left;
    span {
      font-size: 12px;
    }
  }
  .el-pager {
    li {
      color: #6a87ac;
      padding: 0;
      min-width: 30px;
    }
    .active {
      color: #fff;
      background: #348efc;
      font-size: 12px;
    }
  }
  .el-pagination__total,
  .el-pagination__jump {
    color: #6a87ac;
  }
  .el-input__inner {
    border: 1px solid #d5eafb;
    border-radius: 0;
  }
}
.members-checked {
  background-color: #eff4fa;
  border-radius: 4px;
  padding-bottom: 30px;
  .title {
    color: #999;
    border-bottom: 1px solid #ddd;
    padding-left: 40px;
  }
  .container {
    height: 200px;
    overflow-y: scroll;
  }
  .tree-top-level {
    padding-left: 20px;
    .el-tag {
      background-color: #fff;
      margin: 5px 10px 5px 0;
    }
  }
}
</style>